<?php

namespace App\Http\Controllers\Api;
use App\Blocks\User;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Wechat\ServerController;
use EasyWeChat\Factory;
use Illuminate\Http\Request;

class UserController extends Controller {

    public function weixinCallback(Request $request){
        $app = Factory::officialAccount(\Config::get('wechat.official_account.default'));
        $oauth = $app->oauth;
        $user = $oauth->user();
        $userBlock = new User();
        $userInfo = $userBlock->getUserByWxOpenid($user->getId());
        if(!$userInfo){
            $wxuser = $user->getOriginal();
            \Log::debug(json_encode($wxuser));
            global $wechatId;
            $wechatId = 0;

            if($request->has('inviter_id')) {
                $inviter_id = $request->get('inviter_id');
            }
            $saveUserData = [
                'wechat_id'         => $wechatId,
                'subscribe_time'    => isset($wxuser['subscribe_time'])?date('Y-m-d H:i:s', $wxuser['subscribe_time']):null,
                'openid'            => $wxuser['openid'],
                'nickname'          => isset($wxuser['nickname'])?$wxuser['nickname']:null,
                'city'              => isset($wxuser['city'])?$wxuser['city']:null,
                'province'          => isset($wxuser['province'])?$wxuser['province']:null,
                'country'           => isset($wxuser['country'])?$wxuser['country']:null,
                'sex'               => isset($wxuser['sex'])?$wxuser['sex']:null,
                'headimgurl'        => isset($wxuser['headimgurl'])?$wxuser['headimgurl']:null,
                'subscribe'         => isset($wxuser['subscribe'])?$wxuser['subscribe']:0,
                'create_time'       => date('Y-m-d H:i:s', time()),
                'inviter_id'        =>isset($inviter_id)?$inviter_id:null,
            ];
            $userId = $userBlock->saveUserByWeixin($saveUserData);

            if($userId){
                $userInfo = [
                    'openid' => $saveUserData['openid'],
                    'wx_openid' => $saveUserData['openid'],
                    'headimgurl' => $saveUserData['headimgurl'],
                    'nick_name' => $saveUserData['nickname'],
                    'mobile' => null,
                    'id' => $userId,
                ];

                $userInfo = (object)$userInfo;
            }
        }

        if(isset($userInfo->id)){
            if(isset($userInfo->create_time)){
                unset($userInfo->create_time);
            }

            $sessionKey = md5($userInfo->wx_openid);
            \Cache::put($sessionKey, $userInfo, \Config::get('session.lifetime'));

            $userInfo->token = $sessionKey;

            if($request->has('redirect')){
                $redirect = $request->get('redirect');
                $url = env('WEB_URL').'/index';
                if($url === $redirect){
                    $url = env('WEB_URL').'/index';
                }

                $url .= "?token={$userInfo->token}";
                return redirect($url);
            }
            return response()->json($userInfo);
        }else{
            return response()->json(['error' => '登录失败']);
        }
    }
}